<style>
    #manager-list-content .card{
        margin-top:20px;
    }
    #manager-list-content .card-block{
        overflow-x: auto;
    }
    #manager-list-table tbody tr:hover{
        background-color: #74cbea;
    }
    #manager-info-details td{
        border:0;
    }

    /*edit card*/
    .form-tips{
        font-size:0.7em;
    }
    .state-init{
        display:none;
    }
    .state-error{
        display: block;
        color:red;
    }
</style>
<div id="manager-list-content" class="container animated fadeIn">
    <div class="row">

        <div class="center-block col-sm-8">
            <div class="card">
                <div class="card-header">
                    <i class="fa fa-align-justify"></i>
                    <strong>باشقۇرغۇچىلار تىزىملىكى</strong>
                    <div class="card-actions">
                        <a href="#" class="btn-close"><i class="icon-close"></i></a>
                    </div>
                </div>
                <div class="card-block">
                    <table id="manager-list-table" class="table table-striped" >
                        <thead>
                        <tr>
                            <th>نامى</th>
                            <th>تېلفۇن نۇمۇرى</th>
                            <th>ئادېرىسى</th>
                        </tr>
                        </thead>
                        <tbody>

                        </tbody>
                    </table>
                    <ul class="pagination">
                        <li class="page-item"><a class="page-link" href="#">ئالدىنقى بەت</a>
                        </li>
                        <li class="page-item active">
                            <a class="page-link" href="#">1</a>
                        </li>
                        <li class="page-item"><a class="page-link" href="#">2</a>
                        </li>
                        <li class="page-item"><a class="page-link" href="#">3</a>
                        </li>
                        <li class="page-item"><a class="page-link" href="#">4</a>
                        </li>
                        <li class="page-item"><a class="page-link" href="#">كېيىنكى بەت</a>
                        </li>
                    </ul>
                </div>
            </div>
        </div>

        <div class="col-sm-4">
            <div id="manager-info-details" class="card" style="display:none;">
                <div class="card-header">
                    <i class="fa fa-info-circle"></i>
                    <strong>تەپسىلاتى</strong>
                    <div class="card-actions">
                        <a href="#" class="btn-close"><i class="icon-close"></i></a>
                    </div>
                </div>
                <div class="card-block">

                </div>
                <div class="card-footer">
                    <button id="manager-edit-btn" name="" onclick="change2EditCard(this);" class="btn btn-warning"><i class="fa fa-edit"></i> تەھرىرلەش </button>
                    <button name="" onclick="deleteThisMgr(this);" class="btn btn-danger"><i class="fa fa-trash"></i> يۇيۇپ تاشلاش </button>
                </div>
            </div>
        </div>

        <div class="col-sm-8">
            <div id="manager-info-edit" class="card" style="display:none;">
                <div class="card-header">
                    <i class="fa fa-edit"></i>
                    <strong>تەھرىرلەش</strong>
                    <div class="card-actions">
                        <a href="#" class="btn-close"><i class="icon-close"></i></a>
                    </div>
                </div>
                <div class="card-block">

                </div>
                <div class="card-footer">
                    <button type="submit" href="#" onclick="editCompleted();" class="btn btn-primary"><i class="fa fa-check-square-o"></i> تاپشۇرۇمەن </button>
                    <button class="btn btn-danger" onclick="editCanceled();"><i class="fa fa-ban"></i> ۋاز كىچىمەن </button>
                </div>
            </div>
        </div>
    </div>
</div>

<script>

    $("#manager-list-content").ready(function () {
        loadManagerList();

    });

    function loadCities(cityId,mDisId) {
        var selectorCi = $("select[name='sel-cities']");
        net.get('region/cities',null,function (error) {

        },function (response) {
            $.each(response.data,function (index,value) {
                $(selectorCi).append("<option value='"+value.id+"'>"+value.ugName+"   "+value.chName+"</option>");
            });
            //选择
            $("select[name='sel-cities']").val(cityId);
            selCiChanged("select[name='sel-cities']",mDisId);
        });


    }

    /**
     *
     * @param selector
     * @param disId  [Optional]
     */
    function selCiChanged(selector,disId) {
        var cityId = $(selector).val();
        var selectorDi = $("select[name='sel-districts']");
        //清空次级菜单
        $(selectorDi).empty();

        if(cityId == ''){
            //
            $(selector).next().removeClass('state-init').addClass('state-error')
        }else{
            $(selector).next().removeClass('state-error').addClass('state-init');

            net.get('region/districts',{'cityId':cityId},function (error) {

            },function (response) {
                $.each(response.data,function (index,value) {
                    $(selectorDi).append("<option value='"+value.id+"'>"+value.ugName+"   "+value.chName+"</option>");
                });
                //如果有disId,给她选上
                if(disId){
                    $("select[name='sel-districts']").val(disId);
                }
                //第一次提示改变次级菜单 (edit页面可以不提示)
//                $(selectorDi).next().removeClass('state-init').addClass('state-error');
            });
        }

    }

    function loadManagerList() {
        net.get("manager/all",null,function (error) {

        },function (response) {
            $.each(response.data,function (index,value) {
                $("#manager-list-table tbody").append(_templateManagerList(value.mId,value.mName,value.mTel,value.mDistrict.ugName));
            })
        });
    }

    function _templateManagerList(mid,name,tel,location) {
        return "<tr id='list-"+mid+"' onclick='displayDetails(this.id)'><td>"+name+"</td><td>"+tel+"</td><td>"+location+"</td></tr>";
    }

    function _templateManagerDetails(mid,name,email,tel,location,role) {
        return "<table class='table' id='info-"+mid+"'><tr><td>نامى</td><td>"+name+"</td></tr><tr><td>ئېلخەت ساندۇقى</td><td>"+email+"</td></tr><tr><td>تىلفۇن نۇمۇرى</td><td>"+tel+"</td></tr><tr><td>ئادرىسى</td><td>"+location+"</td></tr><tr><td>ھوقۇقى</td><td>"+role+"</td></tr></table>";
    }

    function displayDetails(mid) {
        console.log(mid);
        var id = mid.substring(5);
        //绑定id到btn
        $("#manager-edit-btn").attr('name',id);

        net.get("manager/one",{'mId':id},function (error) {

        },function (response) {
            $("#manager-info-details").show();
            var data = response.data;
            //展示的地址信息
            var village = data.mVillage ? data.mVillage : '' ;
            var location = data.mDistrict.city.ugName +" "+data.mDistrict.ugName+" "+village;

            $("#manager-info-details .card-block").html(_templateManagerDetails(data.mId,data.mName,data.mEmail,data.mTel,location,data.mRole));
        });
    }

    function _templateManagerEdit(mid,name,email,tel,village,role) {
        return '\<form role="form" class="edit-mgr-form" id="'+mid+'">\
            <div class="form-group">\
            <label> نامى </label>\
            <input type="text" class="form-control" onkeyup="goValidate(this);" name="mName" value="'+name+'">\
            <span class="form-tips state-init">ئىناۋەتلىك نام كىرگۈزۈڭ</span>\
        </div>\
\
        <div class="form-group">\
            <label> تىلفۇن نۇمۇرى </label>\
        <input type="number" class="form-control" onchange="goValidate(this);" name="mTel" value="'+tel+'">\
            <span class="form-tips state-init">ئىناۋەتلىك تېلفۇن نۇمۇرى كىرگۈزۈۈڭ</span>\
        </div>\
\
        <div class="form-group">\
            <label> ئېلخەت ساندۇقى </label>\
        <input type="email" class="form-control" onchange="goValidate(this);" name="mEmail" value="'+email+'">\
            <span class="form-tips state-init">ئىناۋەتلىك ئېلخەت ئاددىرىس كىرگۈزۈڭ</span>\
        </div>\
\
       <!-- Location -->\
        <div class="form-group col-sm-6">\
            <label> ۋىلايەت </label>\
            <select name="sel-cities" class="form-control" size="1" onchange="selCiChanged(this);">\
            <option value="">--- تاللاڭ ---</option>\
            </select>\
            <span class="form-tips state-init"> ۋىلايەتنى تاللاڭ</span>\
        </div>\
        <div class="form-group col-sm-6">\
            <label> ناھىيە </label>\
            <select name="sel-districts" class="form-control" size="1" onclick="goValidate(this);">\
\
            </select>\
            <span class="form-tips state-init">ناھىيەنى جەزىملەشتۈرۈڭ</span>\
        </div>\
        <div class="form-group">\
            <label> رايون / يىزا-بازار </label>\
            <input type="text" class="form-control" name="mVillage" value="'+village+'">\
            <span class="form-tips state-init"></span>\
        </div>\
\
        <div class="form-group">\
            <label> شىفىرى </label>\
            <input type="text" class="form-control" name="mPwd" value="123456" placeholder="123456" disabled>\
        <span class="form-tips state-init"></span>\
            </div>\
\
            <div class="form-group">\
            <label> ھوقۇقى </label>\
            <select name="mRole" class="form-control" size="1" onclick="goValidate(this);">\
            <option value="">--- تاللاڭ ---</option>\
            <option value="root"> (خوجىدار (تولۇق ھوقۇق) </option>\
        <option value="storeman"> ئامبارچى </option>\
            <option value="accountant"> بوغالتىر </option>\
            <option value="customer"> خېرىدار </option>\
            </select>\
            <span class="form-tips state-init">باشقۇرغۇچى ھوقۇقىنى تاللاڭ</span>\
        </div>\
        </form>';
    }

    function change2EditCard(btn) {
        console.log("---change to edit card----",$(btn).attr('name'));
        var edit_id = $(btn).attr('name');
        console.log();

        net.get("manager/one",{'mId':edit_id},function (error) {

        },function (response) {
            //关闭这两个card
            $("#manager-info-details .btn-close").click();
            $("#manager-list-content .btn-close").click();

            $("#manager-info-edit").show();
            var data = response.data;
            var mVillage = data.mVillage ? data.mVillage : '';
            $("#manager-info-edit .card-block").html(_templateManagerEdit(data.mId,data.mName,data.mEmail,data.mTel,mVillage,data.mRole));

            loadCities(data.mDistrict.city.id,data.mDistrict.id);

//            $("select[name='sel-cities']").val(data.mDistrict.city.id);
//            $("select[name='sel-districts']").val(data.mDistrict.id);

            $("#manager-info-edit select[name='mRole']").val(data.mRole);
        });

    }
    
    
    function editCompleted() {
        if(!isFormValid()){
            console.log("form not valid...don't submit.");
            return 0;
        }else{
            var serializeArr = $(".edit-mgr-form").serializeArray();
            var Obj = arr2Json(serializeArr);
            Obj['mId'] = $('.edit-mgr-form').attr('id');
            net.post("manager/update",Obj,function (error) {

            },function (response) {
                dia.alert('ئەسكەرتىش','تەھرىرلەش غەلبىلىك بولدى!',['بىلدىم'],'fa fa-check',function (btn_name) {
                    if(btn_name == 'بىلدىم'){
                        $("#manager-info-edit .btn-close").click();
                        //再次加载manager list
                        $(".sidebar .nav-item #manager-list").click();
                    }
                });
            });
        }
    }

    function editCanceled() {
        $("#manager-info-edit .btn-close").click();
        //再次加载manager list
        $(".sidebar .nav-item #manager-list").click();
    }

    function arr2Json(arr){
        var obj = {};
        $(arr).each(function(){
            obj[this.name]=this.value;
        });

        var mDistrict = {
            id:obj['sel-districts'],
            city :{
                id :obj['sel-cities']
            }
        };

        obj['mDistrict'] = mDistrict;

        return obj;
    }

    function goValidate(x) {
        //特殊字符正则
        var containSpecial = RegExp(/[(\~)(\!)(\@)(\#)(\$)(\%)(\^)(\&)(\*)(\()(\))(\-)(\_)(\+)(\=)(\[)(\])(\{)(\})(\|)(\\)(\;)(\:)(\')(\")(\,)(\.)(\/)(\<)(\>)(\?)(\)]+/);

        //mName验证
        if(x.name == "mName") {
            if (containSpecial.test(x.value)) {
                $(x).next().removeClass('state-init').addClass('state-error');
            }else{
                $(x).next().removeClass('state-error').addClass('state-init');
            }
            return;
        }

        //mTel验证
        if(x.name == "mTel") {
            //手机号验证正则
            var telReg = RegExp(/^1[234578]\d{9}$/);

            if (!telReg.test(x.value)) {
                $(x).next().removeClass('state-init').addClass('state-error');
            }else{
                $(x).next().removeClass('state-error').addClass('state-init');
            }
            return;
        }

        //mEmail验证
        if(x.name == "mEmail") {
            //e-mail验证正则
            var emailReg = RegExp(/^[a-z0-9]+([._\\-]*[a-z0-9])*@([a-z0-9]+[-a-z0-9]*[a-z0-9]+.){1,63}[a-z0-9]+$/);

            if (!emailReg.test(x.value)) {
                $(x).next().removeClass('state-init').addClass('state-error');
            }else{
                $(x).next().removeClass('state-error').addClass('state-init');
            }
            return;
        }

        // address 验证
        if(x.name == "sel-districts") {
            //判断父级菜单
            var selectorCi = $("select[name='sel-cities']");
            if(selectorCi.val() == ''){
                selectorCi.next().removeClass('state-init').addClass('state-error');
            }else{
                selectorCi.next().removeClass('state-error').addClass('state-init');
            }

            //判断次级菜单
            if (x.value == "") {
                $(x).next().removeClass('state-init').addClass('state-error');
            }else{
                $(x).next().removeClass('state-error').addClass('state-init');
            }
            return;
        }

        //mRole验证
        if(x.name == "mRole") {
            if (x.value == "") {
                $(x).next().removeClass('state-init').addClass('state-error');
            }else{
                $(x).next().removeClass('state-error').addClass('state-init');
            }
            return;
        }

    }

    function isFormValid() {
        var valid = true;

        $(".edit-mgr-form .form-tips").each(function () {
            if($(this).hasClass("state-error")){
                console.log("error location:",$(this)[0].previousElementSibling.tagName,$(this)[0].previousElementSibling.name);
                valid = false;
                return false;
            }
        });

        if(valid == false){return false}

        $(".edit-mgr-form input").each(function () {
            if(($(this).val() == "" || $(this).val() == "undefined") && this.name != "mVillage"){
                console.log("null value location:",$(this)[0].name);
                var input_name = $(this)[0].name;
                $("input[name='"+input_name+"']").next().removeClass("state-init").addClass("state-error");
                valid = false;
                return false;
            }
        });

        if(valid == false){return false}

        $(".edit-mgr-form select").each(function () {
            if($(this).val() == "" || $(this).val() == "undefined"){
                console.log("null value location:",$(this)[0].name);
                var select_name = $(this)[0].name;
                $("select[name='"+select_name+"']").next().removeClass("state-init").addClass("state-error");
                valid = false;
                return false;
            }
        });

        return valid;
    }


    function deleteThisMgr(btn) {
        console.log("---going to delete this----",$(btn).prev().attr('name'));
        var del_id = $(btn).prev().attr('name');

        dia.alert('جەزىملەشتۇرۇش','راستىنلا يۇيۇپ تاشلامسىز؟ يۇيۇۋەتكەندىن كىيىن ئەسلىگە قايتۇرغىلى بولمايدۇ!',['ياق،ۋاز كىچىمەن','ھەئە،يۇيۇۋىتىمەن'],'fa fa-question',function (btn_name) {
           if(btn_name == 'ياق،ۋاز كىچىمەن'){ return; }

           if(btn_name == 'ھەئە،يۇيۇۋىتىمەن'){
               var data = {'mId':del_id};
               net.get("manager/delete",data,function (error) {

               },function (response) {
                   dia.alert('ئەسكەرتىش','بىر باشقۇرغۇچى يۇيۇپ تاشلاندى!',['بىلدىم'],'fa fa-check',function (btn_name) {
                       $("#manager-info-details .btn-close").click();
                       //再次加载manager list
                       $(".sidebar .nav-item #manager-list").click();
                   });
               })
           }
        });
    }


</script>